package com.tian.service;

import com.tian.entity.RepaymentPlain;
import com.tian.service.LoanCalculatorPlainStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年09月20日 15:53
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 * <p>
 * 按期还本复习
 */
@Slf4j
@Service
public class LoanCalculatorPlainScheduledDebtServicingStrategy implements LoanCalculatorPlainStrategy {
    @Override
    public List<RepaymentPlain> calculator(Integer numberOfPayments, BigDecimal loanAmount, BigDecimal annualInterestRate) {


        return null;
    }

    public static List<RepaymentPlain> doCalculator(Integer numberOfPayments, double loanAmount, double annualInterestRate) {
        double monthlyInterestRate = annualInterestRate / 100 / 12;
        double monthlyPayment = loanAmount * monthlyInterestRate / (1 - Math.pow(1 + monthlyInterestRate, -numberOfPayments));

        DecimalFormat df = new DecimalFormat("#.00");

        System.out.println("期数\t\t本期还款\t\t剩余贷款");
        List<RepaymentPlain> repaymentPlainList = new ArrayList<>();
        for (int i = 1; i <= numberOfPayments; i++) {
            // 本期利息
            double interestPayment = loanAmount * monthlyInterestRate;
            // 本期本金
            double principalPayment = monthlyPayment - interestPayment;
            // 剩余贷款
            loanAmount -= principalPayment;

            RepaymentPlain repaymentPlain = new RepaymentPlain();
            repaymentPlain.setMonth(i);
            repaymentPlain.setMonthInterest(new BigDecimal(interestPayment));
            repaymentPlain.setMonthLoanAmount(new BigDecimal(principalPayment));
            repaymentPlain.setMonthTotalAmount(new BigDecimal(interestPayment + principalPayment));

            repaymentPlainList.add(repaymentPlain);
            System.out.println(i + "\t\t" + df.format(monthlyPayment) + "\t\t" + df.format(loanAmount));
        }
        return repaymentPlainList;
    }
}
